package com.mixsmart.security;

import com.mixsmart.exception.NullArgumentException;
import com.mixsmart.utils.StringUtils;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.SecureRandom;

/**
 * AES算法
 * @author 乌草坡
 * @since 1.0
 * @since 3.1.6 修改AES加密算法
 */
public class AESCoder extends Coder {

    private static final String ALGORITHM = "AES";
    private static final int KEY_SIZE = 128;
    private static final int CACHE_SIZE = 1024;

    private static final String ALGORITHM_MODE = "AES/ECB/PKCS5Padding";

    private static final String ALGORITHM_GCM_MODE = "AES/GCM/PKCS5Padding";

    /**
     * 生成随机密钥
     * @return 返回随机生成的密钥
     */
    public static String getSecretKey() throws Exception {
        return getSecretKey(null, KEY_SIZE);
    }

    /**
     * 生成随机密钥，秘钥结果为Base64编码
     * @return 密钥
     */
    public static String getSecretKeyByBase64() throws Exception {
        return Base64.encodeBase64String(getSecretKey().getBytes());
    }

    /**
     * 获取随机密钥
     * @param seed 密钥种子
     * @return 密钥
     */
    public static String getSecretKey(String seed) throws Exception {
        return getSecretKey(seed, KEY_SIZE);
    }

    /**
     * 生成密钥
     * @param seed 密钥种子
     * @param keySize 密钥长度，默认128；长度只能是128、192、256
     * @return 密钥
     */
    public static String getSecretKey(String seed, int keySize) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        SecureRandom secureRandom;
        if (seed != null && !seed.isEmpty()) {
            secureRandom = new SecureRandom(seed.getBytes());
        } else {
            secureRandom = new SecureRandom();
        }
        if(keySize < 128) {
            keySize = 128;
        } else if(keySize > 256) {
            keySize = 256;
        } else if(keySize != 128 && keySize != 192 && keySize != 256) {
            keySize = 128;
        }
        keyGenerator.init(keySize, secureRandom);
        SecretKey secretKey = keyGenerator.generateKey();
        return encryptBASE64(secretKey.getEncoded());
    }

    /**
     * 加密(AES/ECB/PKCS5Padding)
     * @param data 需要加密的内容
     * @param key 密钥
     * @return 密文
     */
    public static byte[] encrypt(byte[] data, String key) throws Exception {
        byte[] aesKey = key.getBytes();
        SecretKeySpec secretKeySpec = new SecretKeySpec(aesKey, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        return cipher.doFinal(data);
    }

    /**
     * 加密(AES/GCM/PKCS5Padding)
     * @param data 需要加密的内容
     * @param key 密钥
     * @param ivStr 初始向量
     * @return 密文
     */
    public static byte[] encryptGcm(byte[] data, String key, String ivStr) throws Exception {
        return encryptGcm(data, key, 128, ivStr);
    }

    /**
     * 加密(AES/GCM/PKCS5Padding)
     * @param data 需要加密的内容
     * @param key 密钥
     * @param len 密钥长度
     * @param ivStr 初始向量
     * @return 密文
     */
    public static byte[] encryptGcm(byte[] data, String key, int len, String ivStr) throws Exception {
        byte[] aesKey = key.getBytes();
        byte[] iv = ivStr.getBytes();
        SecretKeySpec secretKeySpec = new SecretKeySpec(aesKey, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM_GCM_MODE);
        GCMParameterSpec parameterSpec = new GCMParameterSpec(len, iv);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, parameterSpec);
        return cipher.doFinal(data);
    }

    /**
     * 加密(AES/ECB/PKCS5Padding)
     * @param data 需要加密的内容
     * @param key 密钥
     * @return 返回加密后的值
     */
    public static String encrypt(String data, String key) throws Exception {
        if(StringUtils.isEmpty(data)) {
            throw new NullArgumentException("加密内容不能为空");
        }
        if(StringUtils.isEmpty(key)) {
            throw new NullArgumentException("密钥不能为空");
        }
        byte[] encryptArray = encrypt(data.getBytes(StandardCharsets.UTF_8), key);
        return Base64.encodeBase64String(encryptArray);
    }

    /**
     * 加密(AES/GCM/PKCS5Padding)
     * @param data 需要加密的内容
     * @param key 密钥
     * @param ivStr 初始向量
     * @return 返回加密后的值
     */
    public static String encryptGcm(String data, String key, String ivStr) throws Exception {
        return encryptGcm(data, key, 128, ivStr);
    }

    /**
     * 加密(AES/GCM/PKCS5Padding)
     * @param data 需要加密的内容
     * @param key 密钥
     * @param len 密钥长度
     * @param ivStr 初始向量
     * @return 返回加密后的值
     */
    public static String encryptGcm(String data, String key, int len, String ivStr) throws Exception {
        if(StringUtils.isEmpty(data)) {
            throw new NullArgumentException("加密内容不能为空");
        }
        if(StringUtils.isEmpty(key)) {
            throw new NullArgumentException("密钥不能为空");
        }
        byte[] encryptArray = encryptGcm(data.getBytes(StandardCharsets.UTF_8), key, len, ivStr);
        return encryptBASE64(encryptArray);
    }

    /**
     * 文件加密
     * @param key 密钥
     * @param sourceFilePath 源文件路径
     * @param destFilePath 目标文件路径
     */
    public static void encryptFile(String key, String sourceFilePath, String destFilePath) throws Exception {
        File sourceFile = new File(sourceFilePath);
        File destFile = new File(destFilePath);
        if (sourceFile.exists() && sourceFile.isFile()) {
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            destFile.createNewFile();
            InputStream in = new FileInputStream(sourceFile);
            OutputStream out = new FileOutputStream(destFile);

            byte[] raw = key.getBytes();
            SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM_MODE);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

            CipherInputStream cipherInputStream = new CipherInputStream(in, cipher);
            byte[] cache = new byte[CACHE_SIZE];
            int nRead = 0;
            while ((nRead = cipherInputStream.read(cache)) != -1) {
                out.write(cache, 0, nRead);
                out.flush();
            }
            out.close();
            cipherInputStream.close();
            in.close();
        }
    }

    private static Key handleKey(String key, int keySize) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(key.getBytes());
        keyGenerator.init(keySize, secureRandom);
        return keyGenerator.generateKey();
    }

    /**
     * 解密(AES/ECB/PKCS5Padding)
     * @param data 待解密数据
     * @param key 密钥
     * @return 解密后的数据
     */
    public static byte[] decrypt(byte[] data, String key) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        return cipher.doFinal(data);
    }

    /**
     * 解密(AES/GCM/PKCS5Padding)
     * @param data 待解密数据
     * @param key 密钥
     * @param ivStr 初始向量
     * @return 解密内容
     */
    public static byte[] decryptGcm(byte[] data, String key, String ivStr) throws Exception {
        return decryptGcm(data, key, 128, ivStr);
    }

    /**
     * 解密(AES/GCM/PKCS5Padding)
     * @param data 待解密数据
     * @param key 密钥
     * @param len 密钥长度
     * @param ivStr 初始向量
     * @return 解密内容
     */
    public static byte[] decryptGcm(byte[] data, String key, int len, String ivStr) throws Exception {
        byte[] aesKey = key.getBytes();
        byte[] iv = ivStr.getBytes();
        SecretKeySpec secretKeySpec = new SecretKeySpec(aesKey, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM_GCM_MODE);
        GCMParameterSpec parameterSpec = new GCMParameterSpec(len, iv);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, parameterSpec);
        return cipher.doFinal(data);
    }

    /**
     * 解密(AES/ECB/PKCS5Padding)
     * @param data 加密内容
     * @param key 密钥
     * @return 返回原数据
     */
    public static String decrypt(String data, String key) throws Exception {
        if(StringUtils.isEmpty(data)) {
            throw new NullArgumentException("解密内容不能为空");
        }
        if(StringUtils.isEmpty(key)) {
            throw new NullArgumentException("密钥不能为空");
        }
        byte[] bytes = decrypt(decryptBASE64(data), key);
        return new String(bytes, StandardCharsets.UTF_8);
    }

    /**
     * 解密(AES/GCM/PKCS5Padding)
     * @param data 加密内容
     * @param key 密钥
     * @param ivStr 初始向量
     * @return 返回原数据
     */
    public static String decryptGcm(String data, String key, String ivStr) throws Exception {
        return decryptGcm(data, key, 128, ivStr);
    }

    /**
     * 解密(AES/GCM/PKCS5Padding)
     * @param data 加密内容
     * @param key 密钥
     * @param len 密钥长度
     * @param ivStr 初始向量
     * @return 返回原数据
     */
    public static String decryptGcm(String data, String key, int len, String ivStr) throws Exception {
        if(StringUtils.isEmpty(data)) {
            throw new NullArgumentException("解密内容不能为空");
        }
        if(StringUtils.isEmpty(key)) {
            throw new NullArgumentException("密钥不能为空");
        }
        byte[] bytes = decryptGcm(decryptBASE64(data), key, len, ivStr);
        return new String(bytes);
    }

    /**
     * 文件解密
     * @param key 密钥
     * @param sourceFilePath 源文件路径
     * @param destFilePath 目标文件路径
     */
    public static void decryptFile(String key, String sourceFilePath, String destFilePath) throws Exception {
        File sourceFile = new File(sourceFilePath);
        File destFile = new File(destFilePath);
        if (sourceFile.exists() && sourceFile.isFile()) {
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            destFile.createNewFile();
            FileInputStream in = new FileInputStream(sourceFile);
            FileOutputStream out = new FileOutputStream(destFile);

            byte[] raw = key.getBytes();
            SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM_MODE);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            CipherOutputStream cipherOutputStream = new CipherOutputStream(out, cipher);
            byte[] cache = new byte[CACHE_SIZE];
            int nRead = 0;
            while ((nRead = in.read(cache)) != -1) {
                cipherOutputStream.write(cache, 0, nRead);
                cipherOutputStream.flush();
            }
            cipherOutputStream.close();
            out.close();
            in.close();
        }
    }

    /**
     * 转换密钥
     * @param key 密钥
     * @return 密钥
     */
    private static Key toKey(byte[] key) {
        return new SecretKeySpec(key, ALGORITHM);
    }

}
